package cn.fourhundredandeighteen.service.impl;

import cn.fourhundredandeighteen.dao.CourseDao;
import cn.fourhundredandeighteen.dao.StudentCourseDao;

import cn.fourhundredandeighteen.entity.StudentCourse;
import cn.fourhundredandeighteen.service.StudentCourseService;
import cn.fourhundredandeighteen.utill.MysqlConnect;
import cn.fourhundredandeighteen.utill.NumberUtil;
import org.apache.ibatis.reflection.ArrayUtil;

import java.util.List;

/**
 * @description:
 * @author: liuyongqi
 * @time: 2020/12/16
 */
public class StudentCourseServiceImpl implements StudentCourseService {

    @Override
    public List<StudentCourse> selectCourseToStudent(Long courseId) {
        StudentCourseDao studentCourseDao=MysqlConnect.into().getMapper(StudentCourseDao.class);
        try {
            List<StudentCourse> studentCourses = studentCourseDao.selectCourseToStudent(courseId);
            MysqlConnect.destroy();
            return studentCourses;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<StudentCourse> selectStudentToCourse(Long studentId) {
        StudentCourseDao studentCourseDao=MysqlConnect.into().getMapper(StudentCourseDao.class);
        try {
            List<StudentCourse> studentCourses = studentCourseDao.selectStudentToCourse(studentId);
            MysqlConnect.destroy();
            return studentCourses;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int saveStudentToCourse(Long studentId, Long courseId) {
        StudentCourseDao studentCourseDao= MysqlConnect.into().getMapper(StudentCourseDao.class);
        CourseDao courseDao=MysqlConnect.into().getMapper(CourseDao.class);
        //保存对象
        StudentCourse studentCourse=new StudentCourse();
        studentCourse.setCourseId(courseId);
        studentCourse.setStudentId(studentId);
        studentCourse.setId(NumberUtil.genNo());
            //检查是否存在
        int i = studentCourseDao.selectStudentCourse(courseId, studentId);
        System.out.println("test"+i);
        if (i<=0) {
                //说明学生没选这个课程就保存数据
                int insert = studentCourseDao.insert(studentCourse);
                //更新课程人数
                courseDao.updataStudentCount(courseId,1);
                MysqlConnect.destroy();
                if (insert>0)
                    return insert;
                else
                    return 0;
            }else {
                MysqlConnect.destroy();
                return 0;
            }
    }
}
